//
//  InviteFriendsViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/11/21.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "InviteFriendsViewController.h"
#import "InviteListRootViewController.h"
#import "UserManager.h"
#import "NSString+Category.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface InviteFriendsViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *contentScrollView;
@property (nonatomic, strong) UIImageView *qrCodeImageView;
@property (nonatomic, strong) UILabel *invitationCodeLabel;
@property (nonatomic, strong) UIButton *invitationBtn;
@property (nonatomic, strong) UILabel *ruleLabel;
@property (nonatomic, strong) UILabel *rewardLabel;
@property (nonatomic, strong) UILabel *secondrewardLabel;

@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UIButton *saveImgBtn;
@end

@implementation InviteFriendsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = kLocalizedString(@"邀请好友",nil);

    [self initSubViews];
    [self startLoading];
    [self getRewardRate];
}

#pragma mark - NetWork
- (void)getRewardRate
{
    @weak(self)
    [UserManager getRewardRate:^(id data, HttpRequestResult result, NSString *msg) {
        [self stopLoading];
        if (result == kHttpRequestResultNormal) {
//            NSString *rewardLabelText = [NSString stringWithFormat:@"%@",kLocalizedString(@"直接邀请的好友挖矿可获得5%的收益。并且邀请好友可加速释放AKB。",nil)];
//            NSMutableAttributedString *arrString = [NSString textWithString:rewardLabelText textColor:UIColorFromRGB(0xffffff) font:[UIFont systemFontOfSize:14] lineSpacing:8];
//            CGFloat height = [NSString labelHeightWithAttributedString:arrString sizeWidth:self_weak_.scrollView.width - 30];
//            self_weak_.rewardLabel.attributedText = arrString;
//            self_weak_.rewardLabel.frame = CGRectMake(15, self_weak_.ruleLabel.bottom + 16, self_weak_.scrollView.width - 30, height);
            
//            NSString *secondText = [NSString stringWithFormat:@"%@%@%@",kLocalizedString(@"2. 二级好友挖矿后，可获得好友收益的",nil),[data[@"data"]objectForKey:@"rewardRate2"],kLocalizedString(@"作为奖励，奖励当日返还。",nil)];
//            NSMutableAttributedString *secondArrString = [NSString textWithString:secondText textColor:UIColorFromRGB(0xffffff) font:[UIFont systemFontOfSize:14] lineSpacing:8];
//            CGFloat secondHeight = [NSString labelHeightWithAttributedString:arrString sizeWidth:self_weak_.scrollView.width - 30];
//            self_weak_.secondrewardLabel.attributedText = secondArrString;
//            self_weak_.secondrewardLabel.frame = CGRectMake(15, self_weak_.rewardLabel.bottom + 20, self_weak_.scrollView.width -30, secondHeight);
//            self_weak_.scrollView.contentSize = CGSizeMake(0, self_weak_.secondrewardLabel.bottom + (HFIPhone5 ? 28 : 0) + ([[CBTLanguageManager shareInstance].currentLanguage isEqualToString:@"en-CN"] ? 23 : 0));
        }
        else {
            self_weak_.ruleLabel.hidden = YES;
            self_weak_.rewardLabel.hidden = YES;
        }
    }];
}

#pragma mark - OtherAction

- (void)rightButtonItemAction
{
    InviteListRootViewController *inviteListVC = [[InviteListRootViewController alloc]init];
    [self.navigationController pushViewController:inviteListVC animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.rightButton removeFromSuperview];
    [self.saveImgBtn removeFromSuperview];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)saveScreenImage {
    UIImageWriteToSavedPhotosAlbum(self.qrCodeImageView.image,self,@selector(image:didFinishSavingWithError:contextInfo:),nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        [HFStatusView showFailureMessage:kLocalizedString(@"图片保存失败",nil)];
    } else {
        [HFStatusView showSuccessMessage:kLocalizedString(@"图片保存成功",nil)];
    }
}


-(UIImage *)captureImageFromView:(UIView *)view{
    
    UIGraphicsBeginImageContextWithOptions(self.contentScrollView.frame.size,NO, 0);
    
    [[UIColor clearColor] setFill];
    
    [[UIBezierPath bezierPathWithRect:self.contentScrollView.bounds] fill];
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    [self.contentScrollView.layer renderInContext:ctx];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //navRight
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:17];
    [self.rightButton setTitle:kLocalizedString(@"邀请明细",nil) forState:UIControlStateNormal];
    [self.rightButton addTarget:self action:@selector(rightButtonItemAction) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:self.rightButton];
    [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(0);
    }];
    
    self.saveImgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.saveImgBtn setImage:[UIImage imageNamed:@"all_baocun"] forState:UIControlStateNormal];
    [self.saveImgBtn addTarget:self action:@selector(saveScreenImage) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:self.saveImgBtn];
    [self.saveImgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.rightButton.mas_left).offset(0);
        make.width.mas_equalTo(60);
        make.width.height.mas_equalTo(40);
        make.centerY.mas_equalTo(0);
    }];
}

#pragma mark - InitSubViews
- (void)initSubViews
{

    //contentView
    self.contentScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-HFNavigationHeight)];
    self.contentScrollView.backgroundColor = UIColorFromRGB(0xFFA981);
    [self.view addSubview:self.contentScrollView];
    
    UIImageView *bgImage = [[UIImageView alloc]initWithFrame:self.contentScrollView.bounds];
    [self.contentScrollView addSubview:bgImage];
    bgImage.image = [UIImage imageNamed:@"yaoqing_bg"];
//    bgImage.clipsToBounds = YES;
//    bgImage.contentMode = UIViewContentModeScaleToFill;
    
    UILabel *inviteTitleLB = [[UILabel alloc]init];
    [self.contentScrollView addSubview:inviteTitleLB];
    inviteTitleLB.textColor = [UIColor whiteColor];
    inviteTitleLB.text = kLocalizedString(@"邀请好友",nil);
    inviteTitleLB.font = [UIFont boldSystemFontOfSize:68];
    
    UIView *whiteView = [[UIView alloc]init];
    whiteView.frame = CGRectMake(18, 220, SCREEN_WIDTH-36, 388);
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.layer.cornerRadius = 5;
    [self.contentScrollView addSubview:whiteView];
    
    NSString *currectLanguageStr = [CBTLanguageManager shareInstance].currentLanguage;
    
    if (HFTopStatusHeight <= 21) {
        //非X系列
        whiteView.frame = CGRectMake(18, 175, SCREEN_WIDTH-36, 388);
        
        if ([currectLanguageStr hasPrefix:@"en"]) {
            inviteTitleLB.font = [UIFont boldSystemFontOfSize:48];
            [inviteTitleLB mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(60);
                make.centerX.mas_equalTo(0);
            }];
        }
        else{
            inviteTitleLB.font = [UIFont boldSystemFontOfSize:68];
            [inviteTitleLB mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(50);
                make.centerX.mas_equalTo(0);
            }];
        }
    }
    else{
        whiteView.frame = CGRectMake(18, 210, SCREEN_WIDTH-36, 388);

        if ([currectLanguageStr hasPrefix:@"en"]) {
            inviteTitleLB.font = [UIFont boldSystemFontOfSize:50];
            [inviteTitleLB mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(78);
                make.centerX.mas_equalTo(0);
            }];
        }
        else{
            inviteTitleLB.font = [UIFont boldSystemFontOfSize:68];
            [inviteTitleLB mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(60);
                make.centerX.mas_equalTo(0);
            }];
        }
    }
    
    _qrCodeImageView = [[UIImageView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-138-36)/2.0, 27, 138, 138)];
    _qrCodeImageView.backgroundColor = UIColorFromRGB(0xdbdbdb);
    _qrCodeImageView.image = [UIImage createNonInterpolatedUIImageWithString:[NSString stringWithFormat:@"%@/app/register.html?avatar=%@",kBaseURL_STATIC,[CBTLocalUserManager sharedInstance].avatar] withSize:180];
    [whiteView addSubview:_qrCodeImageView];
    
    _invitationCodeLabel = [[UILabel alloc]initWithFrame:CGRectMake(32, 182, SCREEN_WIDTH - 100, 20)];
    _invitationCodeLabel.textAlignment = NSTextAlignmentCenter;
    _invitationCodeLabel.userInteractionEnabled = YES;
    _invitationCodeLabel.font = [UIFont systemFontOfSize:18];
    _invitationCodeLabel.text = kLocalizedString(@"复制邀请码",nil);
    _invitationCodeLabel.textColor = UIColorFromRGB(0xFF6F41);
    [_invitationCodeLabel bk_whenTapped:^{
        [HFStatusView showSuccessMessage:kLocalizedString(@"复制成功",nil)];
        UIPasteboard *pboard = [UIPasteboard generalPasteboard];
        pboard.string = [CBTLocalUserManager sharedInstance].avatar;
    }];

    [whiteView addSubview:_invitationCodeLabel];
    
    _invitationBtn = [[UIButton alloc]initWithFrame:CGRectMake(22, 215, SCREEN_WIDTH - 80,55)];
    _invitationBtn.layer.cornerRadius  = 5;
    _invitationBtn.layer.masksToBounds = YES;
    [_invitationBtn addTarget:self action:@selector(invitationBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_invitationBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    _invitationBtn.backgroundColor = UIColorFromRGB(0xFF6A3A);
    _invitationBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [_invitationBtn setTitle:kLocalizedString(@"立刻邀请好友", nil) forState:(UIControlStateNormal)];
    [whiteView addSubview:_invitationBtn];
    
    _ruleLabel = [[UILabel alloc]initWithFrame:CGRectMake(27, 289, 200, 16)];
    _ruleLabel.font = [UIFont systemFontOfSize:14];
    _ruleLabel.textColor = UIColorFromRGB(0xFF6F41);
    _ruleLabel.text = kLocalizedString(@"奖励规则", nil);
    [whiteView addSubview:_ruleLabel];
   
    _rewardLabel = [[UILabel alloc]init];
    _rewardLabel.font = [UIFont systemFontOfSize:12];
    _rewardLabel.numberOfLines = 0;
    _rewardLabel.textColor = UIColorFromRGB(0x666666);
    _rewardLabel.text = kLocalizedString(@"直接邀请的好友挖矿可获得5%的收益。并且邀请好友可加速释放PC。", nil);
    [whiteView addSubview:_rewardLabel];
    [_rewardLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(27);
        make.top.mas_equalTo(316);
        make.width.mas_equalTo(SCREEN_WIDTH-36-54);
        make.height.lessThanOrEqualTo(@50);
    }];
    
//    _secondrewardLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, _rewardLabel.bottom + 20, _scrollView.width - 30, 0)];
//    _secondrewardLabel.font = [UIFont systemFontOfSize:14];
//    _secondrewardLabel.numberOfLines = 0;
//    _secondrewardLabel.textAlignment = NSTextAlignmentLeft;
//    _secondrewardLabel.lineBreakMode = NSLineBreakByCharWrapping;
//    _secondrewardLabel.textColor = UIColorFromRGB(0xffffff);
//    [whiteView addSubview:_secondrewardLabel];
}

- (void)invitationBtnAction:(UIButton *)btn
{
    [HFAlert showHFAlertInViewController:self title:kLocalizedString(@"复制成功",nil) message:nil cancleButtonTitle:nil okButtonTitle:kLocalizedString(@"确定",nil) cancelClickHandle:nil okClickHandle:^{
        UIPasteboard *pboard = [UIPasteboard generalPasteboard];
        pboard.string = [NSString stringWithFormat:@"%@/app/register.html?avatar=%@",kBaseURL_STATIC,[CBTLocalUserManager sharedInstance].avatar];
        [HFStatusView showSuccessMessage:kLocalizedString(@"已复制到剪贴板",nil)];
    }];
}

@end
